package com.qdxwx.manage.controller.user;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.manager.ManagerService;
import com.qdxwx.data.service.teacher.TeacherService;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.manage.annotation.Log;
import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.manage.controller.BaseController;
import com.qdxwx.models.enums.BusinessType;
import com.qdxwx.models.manager.Manager;
import com.qdxwx.models.teacher.Teacher;
import com.qdxwx.models.user.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 用户(前台用户)Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/user")
public class UserEditController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private ManagerService managerService;

    /**
     * 新增用户(前台用户)
     */
    @GetMapping("/add.html")
    public String add() {
        return "user/user-add";
    }

    /**
     * 新增保存用户(前台用户)
     */
    @Permissions("user:add")
    @Log(title = "添加用户", businessType = BusinessType.INSERT)
    @PostMapping("/add.json")
    @ResponseBody
    public AjaxResult addSave(HttpServletRequest request) {
        String mobile = request.getParameter("mobile");
        if (!TKString.isMobile(mobile)) return error("请输入正确的手机号码");
        if (userService.getByMobile(mobile) != null) return error("该手机号码已注册！");
        String loginName = request.getParameter("loginName");
        if (TKString.isEmpty(loginName)) return error("请输入用户账号");
        if (userService.getByLoginName(loginName) != null) return error("该账号名已注册！");
        String userName = request.getParameter("userName");
        if (TKString.isEmpty(userName)) return error("请输入用户名");
        String email = request.getParameter("email");
        if (TKString.isNotEmpty(email) && !TKString.isEmail(email)) return error("请输入正确的邮箱地址");
        User user = new User();
        user.setCompanyId(1);
        user.setRegisterFrom("admin");
        user.setMobile(mobile);
        user.setLoginName(loginName);
        user.setRealName(userName);
        user.setUserName(userName);
        user.setEmail(email);
        user.setSex(TKConvert.toInteger(request.getParameter("sex")));
        user.setAge(TKConvert.toInteger(request.getParameter("age")));
        user.setIsAvailable(TKConvert.toInteger(request.getParameter("isAvailable"), 1));
        user.setPassword(TKConvert.toMD5(TKString.getRanString(10)));
        long row = userService.insert(user);
        if (row > 0) {
            //如果有教师更新userId
            Teacher teacher = teacherService.getByMobile(user.getMobile());
            if (teacher != null) {
                teacher.setUserId(user.getUserId());
                teacherService.update(teacher);
            }
            //如果有管理员更新userId
            Manager manager = managerService.getByMobile(user.getMobile());
            if (manager != null) {
                manager.setUserId(user.getUserId());
                managerService.update(manager);
            }
        }
        return row > 0 ? success() : error();
    }

    /**
     * 修改用户(前台用户)
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") long userId, ModelMap mmap) {
        if (userId < 1) return error500;
        User user = userService.get(userId);
        if (user == null) return error500;
        mmap.put("user", user);
        return "user/user-edit";
    }

    /**
     * 修改保存用户(前台用户)
     */
    @Permissions("user:edit")
    @Log(title = "编辑用户", businessType = BusinessType.UPDATE)
    @PostMapping("/edit.json")
    @ResponseBody
    public AjaxResult editSave(HttpServletRequest request) {
        long userId = TKConvert.toLong(request.getParameter("userId"));
        if (userId < 1) return error("找不到用户id");
        User user = userService.get(userId);
        if (user == null) return error("找不到id为:" + userId + "的用户");
        String userName = request.getParameter("userName");
        if (TKString.isEmpty(userName)) return error("请输入用户名称");
        String email = request.getParameter("email");
        if (TKString.isNotEmpty(email) && !TKString.isEmail(email)) return error("请输入正确的邮箱地址");
        user.setUserName(userName);
        user.setEmail(email);
        user.setSex(TKConvert.toInteger(request.getParameter("sex")));
        user.setAge(TKConvert.toInteger(request.getParameter("age")));
        user.setIsAvailable(TKConvert.toInteger(request.getParameter("isAvailable"), 1));
        user.setPassword(TKConvert.toMD5(TKString.getRanString(10)));
        return userService.update(user) > 0 ? success() : error();
    }

    /**
     * 禁用或启用用户(前台用户)
     */
    @Permissions("user:edit")
    @Log(title = "更改用户状态", businessType = BusinessType.UPDATE)
    @PostMapping("/status.json")
    @ResponseBody
    public AjaxResult openOrClose(HttpServletRequest request) {
        long userId = TKConvert.toLong(request.getParameter("userId"));
        if (userId < 1) return error("参数异常");
        User user = new User();
        user.setUserId(userId);
        user.setIsAvailable(TKConvert.toInteger(request.getParameter("isAvailable"), 1));
        return toAjax(userService.update(user));
    }
}
